package _2022.hot100._494_目标和;

import java.util.ArrayList;
import java.util.List;

/**
 * @author： YHSimon
 * @date： 2022-06-11 08:45
 */
public class Solution {
    private int[] multi = new int[]{1, -1};
    private int ans = 0;

    public int findTargetSumWays(int[] nums, int target) {
        List<List<Integer>> combinations = new ArrayList<>();
        // traceback(nums, 0, combinations, new ArrayList<>(),0,target);
        traceback(nums, 0, 0, target);
        // System.out.println(combinations.size());

        return ans;
    }

    public void traceback(int[] nums, int start, int sum, int target) {
        if (start == nums.length) {
            // combinations.add(new ArrayList<>(combine));
            if (sum == target) {
                ans++;
            }
            return;
        }
        for (int i = 0; i < 2; i++) {
            // combine.add(nums[start]*multi[i]);
            traceback(nums, start + 1, sum + nums[start] * multi[i], target);
            // combine.remove(combine.size() - 1);
        }


    }

    // 动态规划
    public int findTargetSumWays2(int[] nums, int target) {
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        int diff = sum - target;
        if (diff < 0 || diff % 2 != 0) {
            return 0;
        }
        int n = nums.length, neg = diff / 2;
        int[][] dp = new int[n + 1][neg + 1];
        dp[0][0] = 1;
        for (int i = 1; i <= n; i++) {
            int num = nums[i - 1];
            for (int j = 0; j <= neg; j++) {
                dp[i][j] = dp[i - 1][j];
                if (j >= num) {
                    dp[i][j] += dp[i - 1][j - num];
                }
            }
        }
        return dp[n][neg];
    }


    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.findTargetSumWays(new int[]{1, 1, 1, 1, 1}, 3));
    }
}
